package com.zen.lon.open.remote.httprequest.interceptor;

import java.io.IOException;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

/**
 * @author ZonLen since on 2022/5/9 下午4:50
 */
public class RestTemplateTraceInterceptor implements ClientHttpRequestInterceptor {

  private static final String TRACE_ID = "TRACE_ID";

  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body,
      ClientHttpRequestExecution execution) throws IOException {
    // 传递链路ID
    if (StringUtils.isNotEmpty(MDC.get(TRACE_ID))) {
      request.getHeaders().add(TRACE_ID, MDC.get(TRACE_ID));
    } else {
      request.getHeaders().add(TRACE_ID, UUID.randomUUID().toString().replace("-", ""));
    }
    return execution.execute(request, body);
  }
}
